package com.kcht.sylyg08.service.impl;

import com.kcht.adp.common.ThreadManager;
import com.kcht.adp.common.log.Logger;
import com.kcht.sylyg08.dao.IContainerStatusTransformRecordDao;
import com.kcht.sylyg08.dao.ICurrentContainerStatusDao;
import com.kcht.sylyg08.dao.IInterveneRecordDao;
import com.kcht.sylyg08.dao.IMaterialContainerBoundDao;
import com.kcht.sylyg08.service.IContainerStatusService;
import com.kcht.sylyg08.service.IReportToWOMS;
import com.kcht.sylyg08.service.ITaskService;
import com.kcth.sylyg08.entity.*;

import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
  *
  * @Package:        com.kcht.sylyg08.service.impl
  * @Description:     java类作用描述
  * @Author:         lenovo
  * @CreateDate:     2019/5/15 14:14
 */
@Transactional(rollbackOn=Exception.class)
@ApplicationScoped
public class ContainerStatusServiceImpl implements IContainerStatusService {
    @Inject
    private Logger logger;

    /*@EJB
    private IContainerDao cDao;*/

    @EJB
    private ICurrentContainerStatusDao ccsDao;

    @EJB
    private IContainerStatusTransformRecordDao cstrDao;

    @EJB
    private IMaterialContainerBoundDao mcbDao;

    /*@EJB
    private IReaderDao rDao;*/

    @EJB
    private IInterveneRecordDao irDao;

    @Inject
    private IReportToWOMS reportService;

    @Inject
    private ITaskService taskService;

    @Inject
    private ThreadManager threadManager;

    /**
     * 修改料框状态
     *
     * @param containerId 料框编号
     * @param actionTime  动作时间
     * @param ip          阅读器IP
     * @param taskType    任务类型
     */
    @Override
    public void changeContainerStatus(String containerId, long actionTime, String ip, TaskType taskType) {
        CurrentContainerStatus status = ccsDao.getByContainerId(containerId);
        String containerAction = "";
        MaterialContainerBound mcBound = mcbDao.getByContainerId(containerId);
/*        switch (status.getStatus()) {
            case 待入库:
                status.setStatus(ContainerStatus.在库);
                containerAction = "入库";
                break;
            case 在库:
                status.setStatus(ContainerStatus.已出库);
//                mcbDao.delete(mcBound.getId());
                containerAction = "出库";
                break;
            case 待出库:
                status.setStatus(ContainerStatus.已出库);
//                mcbDao.delete(mcBound.getId());
                containerAction = "出库";
                break;
            case 已出库:
                status.setStatus(ContainerStatus.在库);
                containerAction = "退库";
                break;
            case 待返工:
                status.setStatus(ContainerStatus.空框待用);
                containerAction = "返工出库";
                mcbDao.delete(mcBound.getId());
        }*/
        status.setToBeMoven(false);
        status.setChangeTime(new Date());
        ccsDao.merge(status);
        saveContainerStatusTransformRecord(containerId, false);
        String taskId = "";
//        List<Task> tasks = null;
//        if (Objects.isNull(taskType)) {
        Task task = taskService.changeTaskStatus(containerId);
        if (Objects.nonNull(task)) {
            taskId = task.getTaskId();
            taskType = task.getTaskType();
        } else {
//                tasks = taskService.getTasksByMaterial(mcBound.getMaterial());
            task = taskService.getFirstUndoneOutGoingTaskByMaterial(mcBound.getMaterial());
            taskId = task.getTaskId();
            taskType = task.getTaskType();
        }
        /*} else {
            tasks = taskService.changeOutGoingTaskStatus(mcBound.getMaterial());
        }*/
        /*if ("".equals(taskId)) {
            for (Task t : tasks) {
                taskId += t.getTaskId() + ",";
            }
            taskId = taskId.substring(0, taskId.length() - 1);
        }*/
        report(containerId, actionTime, ip, status.getStatus(), taskId, taskType, containerAction, false, null, mcBound.getMaterial(), mcBound.getCount());
    }

    /**
     * 接收任务时修改当前料框状态为待转移
     *
     * @param containerId 料框编号
     * @param taskType    任务类型
     */
    @Override
    public void changeCurrentContainerStatus(String containerId, TaskType taskType, String taskId) {
        CurrentContainerStatus status = ccsDao.getByContainerId(containerId);
        if (Objects.isNull(status)) {
            status = new CurrentContainerStatus();
            status.setContainerId(containerId);
        }
/*        switch (taskType) {
            case PRODUCT_OK:
                status.setStatus(ContainerStatus.待入库);
                break;
            case OUT_GOING:
                status.setStatus(ContainerStatus.待出库);
                break;
            case REPAIR:
                status.setStatus(ContainerStatus.待返工);
                break;
            case RETREAT:
                status.setStatus(ContainerStatus.待入库);
                break;
        }*/
        status.setToBeMoven(true);
        status.setChangeTime(new Date());
        ccsDao.merge(status);
        saveContainerStatusTransformRecord(containerId, false);
//        report(containerId, new Date().getTime(), null, status.getStatus(), taskId, taskType, null, false, null, null);
    }

    /**
     * 人工干预修改料框状态
     *
     * @param containerId 料框编号
     * @param status      料框目标状态
     * @param username    干预者
     * @param details     详情
     */
    @Override
    public void changeContainerStatusByIntervene(String containerId, ContainerStatus status, String username, String details) {
        CurrentContainerStatus currentContainerStatus = ccsDao.getByContainerId(containerId);
        currentContainerStatus.setStatus(status);
/*        switch (status) {
            case 待出库:
                currentContainerStatus.setToBeMoven(true);
                break;
            case 待入库:
                currentContainerStatus.setToBeMoven(true);
                break;
            case 待返工:
                currentContainerStatus.setToBeMoven(true);
                break;
            case 在库:
                currentContainerStatus.setToBeMoven(false);
                break;
            case 已出库:
                currentContainerStatus.setToBeMoven(false);
                break;
            default:
                currentContainerStatus.setToBeMoven(false);
                MaterialContainerBound mcBound = mcbDao.getByContainerId(containerId);
                if (Objects.nonNull(mcBound)) {
                    mcbDao.delete(mcBound.getId());
                }
                break;
        }*/
        currentContainerStatus.setChangeTime(new Date());
        ccsDao.merge(currentContainerStatus);
        boolean isAbnormal = true;
        if (details.contains("woms")) {
            isAbnormal = false;
        }
        saveInterveneRecord(saveContainerStatusTransformRecord(containerId, isAbnormal), status, username, details);
//        report(containerId, new Date().getTime(), null, status, null, TaskType.OUT_GOING, "完成出库", isAbnormal, username, null);
        /*ContainerActionDetails containerActionDetails = new ContainerActionDetails();
        containerActionDetails.setContainerId(containerId);
        containerActionDetails.setRtnCode(-99);
        ADPEventPublisher.publishEvent(containerActionDetails);*/
    }

    @Override
    public void changeOutGoingContainerComplete(String material, String username, long time, String taskId) {
        List<CurrentContainerStatus> statuses = ccsDao.selectListByJPQL("select a from CurrentContainerStatus a where a.status = 6");
        for (CurrentContainerStatus status : statuses) {
            MaterialContainerBound bound = mcbDao.getByContainerId(status.getContainerId());
            if (material.equals(bound.getMaterial())) {
                //status.setStatus(ContainerStatus.空框待用);
                ccsDao.merge(status);
                saveContainerStatusTransformRecord(status.getContainerId(), false);
                mcbDao.delete(bound.getId());
                report(status.getContainerId(), time, null, status.getStatus(), taskId, TaskType.OUT_GOING, "完成出库任务", false, username, material, bound.getCount());
            }
        }
    }

    /**
     * woms更新料框状态
     *
     * @param containerId 料框编号
     * @param status      料框状态
     * @param user        修改人
     */
    /*@Override
    public void UpdateContainerStatus(String containerId, ContainerStatus status, String user) {
        Date date = new Date();
        CurrentContainerStatus ccstatus = ccsDao.getByContainerId(containerId);
        ccstatus.setStatus(status);
        ccstatus.setChangeTime(new Date());
        ccsDao.merge(ccstatus);
        *//*ContainerStatusTransformRecord record = new ContainerStatusTransformRecord();
        record.setContainerId(containerId);
        record.setTransformDate(date);
        cstrDao.save(record);*//*
        saveInterveneRecord(saveContainerStatusTransformRecord(containerId, true), status, user, null);
        *//*InterveneRecord iRecord = new InterveneRecord();
        iRecord.setIntervener(user);
        iRecord.setContainerStatus(status);
        iRecord.setDetails("WOMS修改料框状态");
        iRecord.setContainerStatusTransformRecordId(record.getId());
        irDao.save(iRecord);*//*
        report(containerId, new Date().getTime(), null, status, null, null, null, false, user, null);
    }*/

    /**
     *
     *
     * @param containerStatusTransformRecordId 料框状态修改记录编号
     * @param status                           料框被修改为的状态
     * @param username                         干预者
     * @param details                          详情
     */
    private void saveInterveneRecord(Long containerStatusTransformRecordId, ContainerStatus status, String username, String details) {
        InterveneRecord record = new InterveneRecord();
        record.setContainerStatusTransformRecordId(containerStatusTransformRecordId);
        record.setContainerStatus(status);
        record.setIntervened(username);
        record.setDetails(details);
        irDao.save(record);
    }

    /**
     * 保存料框状态转换记录
     *
     * @param containerId 料框编号
     * @param isAbnormal  是否异常
     * @return 料框状态转换记录编号
     */
    private Long saveContainerStatusTransformRecord(String containerId, boolean isAbnormal) {
        ContainerStatusTransformRecord record = new ContainerStatusTransformRecord();
        record.setIsAbnormal(isAbnormal);
        record.setContainerId(containerId);
        record.setTransformDate(new Date());
        cstrDao.save(record);
        return record.getId();
    }

    /**
     * 上报料框动作给WOMS
     *
     * @param containerId     料框编号
     * @param actionTime      动作时间
     * @param ip              阅读器IP
     * @param status          料框被修改为的状态
     * @param taskId          相关任务编号
     * @param type            相关任务类型
     * @param containerAction 料框动作
     */
    private void report(String containerId, long actionTime, String ip, ContainerStatus status, String taskId,
                        TaskType type, String containerAction, boolean isError, String username, String mateiral, Integer count) {
        RFIDReport report = new RFIDReport();
        report.setRequestUUID(UUID.randomUUID().toString().replaceAll("-", ""));
        report.setActionTime(actionTime);
        report.setReader(ip);
        report.setContainer(containerId);
        report.setMaterial(mateiral);
        report.setTaskId(taskId);
        report.setTaskType(type);
        report.setIntervener(username);
        report.setCount(count);
        report.setContainerAction(containerAction);
        report.setError(isError);
        report.setContainerStatus(status);
        threadManager.post(() -> {
            reportService.report(report, false);
        });
//        reportService.report(report, false);
    }
}
